import React, { Component } from 'react';
import { LockOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';
import '@ant-design/compatible/assets/index.css';
import { Col, Card, Row, Input, message, Button, Form, Spin } from 'antd';
import { connect } from 'dva';
import { encryptedData } from '@/utils/utils';
import { publicKey } from "../../../../../public/global";
import { validateContinuousChar } from '@/utils/validator';
import { specicalChars } from '@/support/constant/common';


const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  accountSetting: state.accountSetting,
  menu: state.menu,
  login: state.login,
  loading: state.loading.effects['accountSetting']
});
class SecurityView extends Component<any, any> {

  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      loading: false
    }
  }

  checkPassword = (rule: any, value: any) => {
    const { menu: { pwdStrategy: { pwdStrategy, pwdStrategyDesc } } } = this.props;
    if (value) {
      const regex = new RegExp(pwdStrategy);
      if (!regex.test(value)) {
        return Promise.reject(`请确认输入的密码，${pwdStrategyDesc}`);
      }
    } else {
      return Promise.reject('请输入密码！');
    }
    return Promise.resolve();
  };
  checkPwd = (rule: any, value: any) => {
    const { menu: { pwdStrategy: { pwdStrategy, pwdStrategyDesc } } } = this.props;
    if (value) {
      const regex = new RegExp(pwdStrategy);
      if (!regex.test(value)) {
        return Promise.reject(`请输入正确的密码，${pwdStrategyDesc}`);
      }else if(/([\dA-Za-z])\1{3,}/.test(value)) {
        return Promise.reject('禁止密码设置4位连续相同的字符');
      } else if(validateContinuousChar(value)) {
        return Promise.reject('禁止密码设置4位连续递增，递减的数字或字母');
      } else if(specicalChars.some(char => value.toLowerCase().indexOf(char.toLowerCase()) > -1 )) {
        return Promise.reject('禁止密码设置4位1qaz，2wsx，3edc，dfm，admin，dftc，dfrd等简单字符');
      }
    } else {
      return Promise.reject('请输入密码');
    }
    return Promise.resolve();
  };
  handleSubmit = () => {
    this.formRef.current?.submit();
  };

  onFinish = (values: any) => {
    const { dispatch } = this.props;
    const obj = {
      currentPwd: encryptedData(values.accountPwd, publicKey), 
      originalPwd: encryptedData(values.accountOriginalPwd, publicKey)
    }
    this.setState({
      loading: true
    })
    dispatch({
      type: 'accountSetting/postObjWithRes',
      payload: {url: '/common/account/modifypwd', ...obj },
      callback: (response: any) => {
        this.setState({
          loading: false
        })
        if (response && response.statusCode === '0') {
          this.formRef.current?.resetFields();
          message.success("密码修改成功！");
          dispatch({
            type: 'login/logout'
          })
        }
      }
    });
  }
  render() {
    const { loading } = this.state
    return (
      <Card bordered={false}>
        <Spin spinning={ loading }>
        <Row gutter={24}>
          <Col span={12}>
            <Form ref={this.formRef} onFinish={this.onFinish} labelCol={{ span: 7 }}>
              <FormItem
                name="accountOriginalPwd"
                label="原始密码"
                rules={[{ required: true, message: '请输入原始密码！' }]}
                hasFeedback
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  maxLength={30}
                  placeholder="请输入原始密码"
                />
              </FormItem>
              <FormItem
                name="accountPwd"
                label="新密码"
                rules={[{ required: true, validator: this.checkPwd }]}
                hasFeedback
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  maxLength={30}
                  placeholder="请输入新密码"
                />
              </FormItem>
              <FormItem
                name="accountPwdCheck"
                label="确认新密码"
                dependencies={['accountPwd']}
                hasFeedback
                rules={[
                  { 
                    required: true,
                    validator: this.checkPassword
                  },
                  ({ getFieldValue }) => {
                    return {
                        validator(_, value) {
                          if (!value || getFieldValue('accountPwd') === value) {
                            return Promise.resolve();
                          }
                          return Promise.reject(new Error('两次输入的密码不匹配！'));
                        },
                      }
                    },
                  ]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  maxLength={30}
                  placeholder="请确认输入的密码"
                  onPressEnter={this.handleSubmit}
                />
              </FormItem>
            </Form>
            <Button type="primary"  onClick={this.handleSubmit} style={{ width: '100%' }}>
              更 新 密 码
            </Button>
          </Col>
        </Row>
        <Row gutter={8}>
          <Col span={12}>
            <span style={{ color: "red" }}>密码修改成功后自动跳转到登录页，请重新登录！</span>
          </Col>
        </Row>
        </Spin>
      </Card>
    );
  }
}
export default connect(mapStateToProps)(SecurityView);
